import React, { useEffect, useRef, useState } from 'react';
import flvjs from 'flv.js';

const VideoPlayer = ({ url, isStreaming }) => {
  const videoRef = useRef(null);
  const flvPlayerRef = useRef(null);
  const [playerError, setPlayerError] = useState(null);
  const retryTimerRef = useRef(null);
  const retryCountRef = useRef(0);
  const maxRetries = 5;  // 增加重试次数

  useEffect(() => {
    console.log('VideoPlayer组件收到URL:', url);
    console.log('isStreaming状态:', isStreaming);
    
    // 销毁任何现有播放器
    destroyFlvPlayer();
    
    // 只有在streaming为true且URL存在时才创建播放器
    if (isStreaming && url) {
      // 延迟3秒再创建播放器，给SRS更多时间准备流
      setTimeout(() => {
        createFlvPlayer();
      }, 3000);
    }
    
    return () => {
      destroyFlvPlayer();
      clearTimeout(retryTimerRef.current);
    };
  }, [url, isStreaming]);

  const destroyFlvPlayer = () => {
    if (flvPlayerRef.current) {
      try {
        flvPlayerRef.current.unload();
        flvPlayerRef.current.detachMediaElement();
        flvPlayerRef.current.destroy();
      } catch (e) {
        console.error('销毁FLV播放器时出错:', e);
      }
      flvPlayerRef.current = null;
    }
    
    if (retryTimerRef.current) {
      clearTimeout(retryTimerRef.current);
      retryTimerRef.current = null;
    }
  };

  const createFlvPlayer = () => {
    const videoElement = videoRef.current;
    if (!videoElement || !isStreaming || !url) {
      console.log('创建FLV播放器条件不满足', {
        videoElement: !!videoElement,
        isStreaming,
        url
      });
      return;
    }
    
    if (!flvjs.isSupported()) {
      setPlayerError('您的浏览器不支持FLV播放');
      return;
    }
    
    // 先清理现有播放器
    destroyFlvPlayer();
    
    try {
      console.log('尝试创建FLV播放器, URL:', url);
      
      // 确保URL格式正确
      const correctedUrl = url.includes('://') ? url : `http://47.94.76.165:18080/live/test.flv`;
      console.log('使用修正后的URL:', correctedUrl);
      
      const player = flvjs.createPlayer({
        type: 'flv',
        url: correctedUrl,
        isLive: true,
        hasAudio: true,
        hasVideo: true,
        cors: true,
        withCredentials: false,
        // 增加更多容错配置
        enableStashBuffer: false,
        stashInitialSize: 128,
        enableWorker: true,
        lazyLoad: false,
        seekType: 'range',
        fixAudioTimestampGap: false, // 修复音频时间戳问题
        accurateSeek: false,
        autoCleanupSourceBuffer: true
      });
      
      player.attachMediaElement(videoElement);
      player.load();
      
      player.on(flvjs.Events.LOADING_COMPLETE, () => {
        console.log('FLV加载完成');
      });
      
      player.on(flvjs.Events.RECOVERED_EARLY_EOF, () => {
        console.log('FLV恢复了提前结束的文件');
      });
      
      player.on(flvjs.Events.ERROR, (errorType, errorDetail) => {
        console.error('FLV播放器错误:', errorType, errorDetail);
        // 提供更详细的错误信息
        const errorMsg = errorDetail ? `${errorType}: ${errorDetail}` : errorType;
        setPlayerError(`播放错误: ${errorMsg}`);
        retryPlay();
      });
      
      player.on(flvjs.Events.MEDIA_INFO, (mediaInfo) => {
        console.log('FLV媒体信息:', mediaInfo);
      });
      
      // 尝试播放
      const playPromise = player.play();
      if (playPromise !== undefined) {
        playPromise.catch(e => {
          console.error('播放视频失败:', e);
          setPlayerError(`播放失败: ${e.message}`);
        });
      }
      
      flvPlayerRef.current = player;
      setPlayerError(null);
    } catch (error) {
      console.error('创建FLV播放器时出错:', error);
      setPlayerError(`创建播放器失败: ${error.message}`);
      retryPlay();
    }
  };

  const retryPlay = () => {
    if (retryCountRef.current >= maxRetries) {
      console.log('已达到最大重试次数');
      retryCountRef.current = 0;
      return;
    }
    
    clearTimeout(retryTimerRef.current);
    retryTimerRef.current = setTimeout(() => {
      console.log(`第 ${retryCountRef.current + 1} 次重试播放...`);
      retryCountRef.current += 1;
      createFlvPlayer();
    }, 2000);
  };

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      <video
        ref={videoRef}
        style={{ width: '100%', height: '100%', backgroundColor: '#000' }}
        controls
        muted={false}
        autoPlay
      />
      {playerError && (
        <div style={{ 
          position: 'absolute', 
          bottom: '10px', 
          left: '10px', 
          right: '10px',
          backgroundColor: 'rgba(255, 0, 0, 0.7)',
          color: 'white',
          padding: '8px',
          borderRadius: '4px'
        }}>
          {playerError}
          <button 
            style={{
              marginLeft: '10px',
              padding: '2px 8px',
              backgroundColor: 'white',
              color: 'black',
              border: 'none',
              borderRadius: '4px'
            }}
            onClick={() => {
              retryCountRef.current = 0;
              createFlvPlayer();
            }}
          >
            重试
          </button>
        </div>
      )}
    </div>
  );
};

export default VideoPlayer; 